package searchAlgorithm;

public class Search {

    /**
     * 二分查找
     *
     * @param arr
     * @param target
     * @return
     */
    public int binarySearch(int[] arr, int target) {

        int start = 0;
        int end = arr.length - 1;

        while (start <= end) {
            int mid = (start + end) / 2;
            //找到结果
            if (arr[mid] == target) {
                return mid;
            }
            //在左边
            if (arr[mid] > target) {
                end = mid - 1;
            }
            //在右边
            if (arr[mid] < target) {
                start = mid + 1;
            }
        }
        return -1;
    }

    /**
     * 二分查找递归写法
     *
     * @param arr
     * @param target
     * @return
     */
    public int binarySearchByRecursion(int[] arr, int target, int start, int end) {

        int mid = (start + end) / 2;
        if (arr[mid] == target) {
            return mid;
        }
        if (arr[mid] < target) {
            return binarySearchByRecursion(arr, target, mid + 1, end);
        }
        if (arr[mid] > target) {
            return binarySearchByRecursion(arr, target, start, mid - 1);
        }
        return -1;
    }


    public static void main(String[] args) {
        Search search = new Search();
        int[] arr = {1, 2, 3, 4, 6, 7, 8, 90, 133};
        int i = search.binarySearch(arr, 1);
        int j = search.binarySearchByRecursion(arr, 1, 0, arr.length - 1);
        System.out.println(i);
        System.out.println(j);
    }
}
